<template>
  <div class="uploadAppointPay">
    <el-dialog :visible.sync="fileUpDialogVisible" title="支付凭证上传" :close-on-click-modal="false">
     <el-form :model="dataForm" ref="dataForm" label-width="100px" style='width: 600px; margin-left:20px;' :rules="roleRules">
       <el-form-item label="备注" prop="remark">
         <el-input type="textarea" v-model="dataForm.remark" :rows="5" :cols="30"></el-input>
       </el-form-item>

        <el-form-item>
         <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :action="uploadUrl"
            ref="upload"
            :before-upload="fnBeforeUpload"
            :on-remove="fnUploadRemove"
            :on-exceed="fnUploadExceed"
            :on-change="fnUploadChange"
            :http-request="fnUploadRequest"
            :limit = 'limit'
            :disabled="disabled"
            :file-list="fileList"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">注：目前仅支持上传图片且大小不能超过20M</div>
          </el-upload>

        </el-form-item>
      </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="fileUpDialogVisible=false">取消</el-button>
          <el-button @click="sureUpload" :loading="submitLoading" type="primary">提交</el-button>
       </div>
    </el-dialog>
  </div>
</template>
<script>
import * as message from "@/constants/message";
import ComponentApi from "@/api/components/component";
import AppointApi from "@/api/appoint/appoint";
import * as Constants from "@/constants/constants";

export default {
  name: 'uploadAppointPay',
  props: {
    /*appointId: {
      type: Number,
      default: null
    }*/
  },
  data() {
    return {
      dataForm: {
        appointId:"",
        fileList:[],
        fileUrls:"",
        remark:""
      },
      ossClient: null,
      chooseFileLength: 0,
      limit: 8,
      uploadUrl: '',
      fileList: [],
      uploadHeaders: {
        authorization: ''
      },
      uploadFileList: [],
      fileUpDialogVisible: false,
      submitLoading: false,
      disabled: false,
      roleRules: {
        /*healthType: [
          { required: true, message: "请选择病情类型", trigger: "change" },
        ],
        healthDate:[
          { required: true, message: '请选择病情日期', trigger: 'change' }
        ]*/
      }
    }
  },
  methods: {
    async fnUploadRequest (option) {
      try {
        const _this = this
        // 已经上传过的不处理：情景先上传成功3个，后补充1个，之前3个会循环调用。
        if (option && option.response && option.response.url) {
          return
        }
        // 当前上传的文件
        let file = option.file
        const fileName = file.name
        // 避免文件名带有多个.
        let fileNameArr = fileName.split("\.");
        const fileType = fileNameArr[fileNameArr.length-1];
        const newName = _this.$Utils.mathRand19() +"."+ fileType;
        console.log(newName,123)
        const storeAs = Constants.OSS_WEB_URL + 'appoint/' + newName;

        _this.ossClient.put(storeAs, file, {}).then(
          function (ret) {
            if (ret.res.statusCode === 200) {
              let realUrl = ret.url.replace(Constants.OSS_URL,Constants.OSS_REAL_URL);
              ret.url = realUrl;
              _this.uploadFileList.push(realUrl)
              // 值回传
              option.response = ret
              return ret
            } else {
              option.onError('上传失败')
            }
          }
        ).catch(function (err) {
          console.error(err)
        })
      } catch (error) {
        console.error(error)
        this.disabled = false
        option.onError('上传失败')
        this.$error(error.message)
      }
    },
    fnUploadChange (file, fileList) {
      this.chooseFileLength = fileList.length
    },
    fnUploadRemove (file, fileList) {
      this.chooseFileLength = fileList.length
    },
    /**
     * el-upload
     * on-exceed	文件超出个数限制时的钩子
     *  */
    fnUploadExceed (files, fileList) {
      let _this = this
      // _this.$message.warning(`当前限制选择 ${_this.files} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      _this.$message.warning(`当前限制最多上传 ${_this.files} 个文件!`)
    },
    fnBeforeUpload (file) {
      const result = this.$Utils.matchType(file.name);
      if (result != 'image') {
        this.$message.error('文件上传格式不支持!');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 20MB!');
        return false;
      }
      return true;
    },
    sureUpload() {
      let _this = this;
      // 判断是否有选择文件
      if (_this.chooseFileLength == 0){
        _this.$message.error('您未选择需上传的文件!')
        return
      }
      _this.submitLoading = true;
      // 请求oss，获取授权
      ComponentApi.uploadOss().then(res => {
          let OSS = require('ali-oss')
          _this.ossClient = new OSS({
            region: Constants.OSS_REGION,
            accessKeyId: res.data.accessKeyId,
            accessKeySecret: res.data.accessKeySecret,
            stsToken: res.data.securityToken,
            bucket: Constants.OSS_BUCKET
          });

        _this.$refs.upload.submit();

        const interval = setInterval(() => {
          if (_this.uploadFileList.length>0 && _this.uploadFileList.length == _this.chooseFileLength){
            _this.dataForm.fileList = _this.uploadFileList
            _this.dataForm.fileUrls = _this.dataForm.fileList.toString()
            // 调用上传预约支付凭证接口
            AppointApi.uploadAppointPayFile(_this.dataForm)
              .then(res => {
                AppointApi.updateAppointState({
                  id: _this.dataForm.appointId,
                  state: 16
                }).then(res => {
                  _this.$Utils.notifySuccess()
                })
                _this.fileUpDialogVisible = false
              }).catch(error => {
              _this.$notify.error({
                title: message.TITLE_ERROR,
                message: "上传失败，请稍后重试"
              })
            })

            // 使用$emit出发父组件的自定义事件
            //this.$emit('uploadHealthList', this.uploadFileList)
            //console.log(666,JSON.stringify(this.uploadFileList))
            _this.submitLoading = false
            clearInterval(interval);
          }
        }, 1000);

      });

    },
    handleCreate(val) {
      this.dataForm.appointId = val
      this.fileList = []
      this.uploadFileList = []
      this.fileUpDialogVisible = true
    }
  }

}
</script>
<style>
</style>
